package com.eyolas.passwordmanager.dao;

import java.sql.SQLException;
import java.util.Iterator;
import java.util.List;

import com.eyolas.passwordmanager.idao.IAccountDao;
import com.eyolas.passwordmanager.model.Account;
import com.eyolas.passwordmanager.model.Category;
import com.eyolas.passwordmanager.utils.SimpleCrypto;
import com.j256.ormlite.dao.BaseDaoImpl;
import com.j256.ormlite.support.ConnectionSource;

/**
 * account dao
 * @author Eyolas
 * @date 24 mai 2012
 */
public class AccountDao extends BaseDaoImpl<Account, Integer> implements IAccountDao{
	public AccountDao(ConnectionSource connectionSource) throws SQLException {
		super(connectionSource, Account.class);
	}
	
	@Override
	public List<Account> getAllByCategoryOrderByName(Category category) throws SQLException{
		return queryBuilder().orderByRaw("acc_name COLLATE NOCASE").where().eq("acc_category", category.getId()).query();
	}
	
	
	@Override
	public boolean updatePassword(String oldPassword, String newPassword) {
		try {
			List<Account> list = queryForAll();
			Iterator<Account> i = list.iterator();
			while(i.hasNext()) {
				Account currentAccount = i.next();
				currentAccount.setPassword(SimpleCrypto.encrypt(newPassword, SimpleCrypto.decrypt(oldPassword, currentAccount.getPassword())));
				update(currentAccount);
			}
		} catch (Exception e) {
			return false;
		}
		
		return true;
	}

	@Override
	public List<Account> getAllByCategory(Category category) throws SQLException {
		return queryBuilder().orderByRaw("acc_name COLLATE NOCASE").where().eq("acc_category", category.getId()).query();
	}

	@Override
	public int deleteByCategory(Category _category) throws SQLException {
		return delete(getAllByCategory(_category));
	}
}
